package multi_thread.advanced.blocking_queue;

import collection.PriorityQueueStudy;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * @author Cheng Jun
 * Description: PriorityBlockingQueue 优先级的阻塞队列 和 PriorityQueue
 * 必须先掌握 PriorityQueue，才能更好学习 PriorityBlockingQueue
 * 读写互斥
 * @version 1.0
 * @date 2022/5/16 14:29
 * @see PriorityQueueStudy
 * @see PriorityBlockingQueue
 */
public class PriorityBlockingQueueExample {
    public static void main(String[] args) {
        // 默认是小根堆，且默认大小为11，可以扩容
        PriorityBlockingQueue<Integer> intPriorityBlockingQueue = new PriorityBlockingQueue<>();
        intPriorityBlockingQueue.offer(1);
        intPriorityBlockingQueue.offer(0);
        intPriorityBlockingQueue.offer(3);
        intPriorityBlockingQueue.offer(2);

        PriorityTakeThread priorityTakeThread = new PriorityTakeThread(intPriorityBlockingQueue);
        priorityTakeThread.start();
    }

    static class PriorityTakeThread extends Thread {
        private PriorityBlockingQueue<Integer> intPriorityBlockingQueue;

        @Override
        public void run() {
            while (true) {
                try {
                    // 阻塞式 take
                    System.out.println(intPriorityBlockingQueue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        PriorityTakeThread(PriorityBlockingQueue<Integer> intPriorityBlockingQueue) {
            this.intPriorityBlockingQueue = intPriorityBlockingQueue;
        }
    }
}
